package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.CommonStatusConstants;
import com.jzo2o.common.constants.ErrorInfo;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.config.SecurityConfig;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.model.dto.request.InstitutionResetPasswordReqDTO;
import com.jzo2o.customer.service.IRegisterService;
import com.jzo2o.customer.service.IServeProviderService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author jianghaijun
 */
@Service
public class RegisterServiceImpl implements IRegisterService {
    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    private IServeProviderService serveProviderService;
    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 注册
     * @param institutionRegisterReqDTO 注册参数
     */
    @Override
    public void register(InstitutionRegisterReqDTO institutionRegisterReqDTO) {
        // 数据校验
        if(StringUtils.isEmpty(institutionRegisterReqDTO.getVerifyCode())){
            throw new BadRequestException("验证码为空，请输入验证码");
        }

        //远程调用publics服务校验验证码是否正确
        boolean verifyResult = smsCodeApi
                .verify(institutionRegisterReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, institutionRegisterReqDTO.getVerifyCode())
                .getIsSuccess();
        if(!verifyResult) {
            throw new BadRequestException("验证码错误，请重新获取");
        }
        // 判断是否注册
        ServeProvider serveProvider = serveProviderService.findByPhoneAndType(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION);
        // 账号禁用校验
        if(serveProvider != null && CommonStatusConstants.USER_STATUS_FREEZE == serveProvider.getStatus()) {
            throw new CommonException(ErrorInfo.Code.ACCOUNT_FREEZED, serveProvider.getAccountLockReason());
        }
        // 自动注册
        if (serveProvider == null) {
            serveProviderService.add(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION, passwordEncoder.encode(institutionRegisterReqDTO.getPassword()));
        }


    }


}
